﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using CMS;
using System.Linq;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Net;

public partial class Users_view : System.Web.UI.Page
{
    public CMS.Functions fn = new CMS.Functions();
    public StoredProcedureValues Results = new StoredProcedureValues();

    public long? Userid;
    public long? UserID
    {
        get { return Userid; }
        set { Userid = value; }
    }

    private int Action;
    public string PictureNameFull = "";
    public string RemoveFancy = "";
    public string PhotoEmptyText = "Click to upload";
    public string ImageUrl = "images/NoImage.jpg";

    protected void Page_Init(object sender, EventArgs e)
    {
        if (CMS.Rights.USR == false) { Response.Redirect("Forbidden.aspx"); }

        if (!CMS.Functions.VerifyLogin.Valid) { Response.Redirect("Login.aspx"); }
        else
        {
            if (Request.QueryString["UserID"] != null) { UserID = Convert.ToInt64(Request.QueryString["UserID"].ToString()); }
            if (Request.QueryString["CMD"] != null) { Action = Convert.ToInt16(Request.QueryString["CMD"].ToString()); }

            Session.Add("UserID", UserID);
            Session.Add("CMD", Action);

            if (!IsPostBack) { FillValues(); }
        }
    }
    public Boolean HasUserImage;
    void FillValues()
    {
        if (Action == CMD.View || Action == CMD.Update || Action == CMD.Delete)
        {
            var Users = CMS.Users.GetUsers(UserID, USR_NAME.Text, null, USR_EMAIL.Text, CMS.Functions.AdministrationID, null, null,null).FirstOrDefault();
            var GetPicture = CMS.Uploads.GetUpload(CMS.Functions.AdministrationID, null, UserID, null, null, null).FirstOrDefault();

            if (Users != null && UserID.HasValue)
            {
                USR_NAME.Text = Users.USR_NAME;
                UsrTitle.Text = " - " + Users.USR_NAME;
                USR_EMAIL.Text = Users.USR_EMAIL;
                USR_ACTIVE.Checked = Users.USR_ACTIVE.Value;
                USR_MASTERUSER.Checked = Users.USR_MASTERUSER.Value;

                if (GetPicture != null)
                {
                    string savePath = "Uploads\\Pictures\\" + CMS.Functions.Administrationname + "\\";
                    
                    if (FancyPhoto.ImageUrl != ImageUrl)
                    {
                        FancyPhoto.ImageUrl = savePath + GetPicture.UPL_GUID + ".jpg";
                        ((Content)Master).FancyPhotoheader(UserID, savePath + GetPicture.UPL_GUID + ".jpg");
                    }
                    else
                    {
                        ((Content)Master).FancyPhotoheader(UserID, ImageUrl);
                    }

                    UPL_NAME.Text = GetPicture.UPL_NAME;
                    PictureNameFull = GetPicture.UPL_NAME;
                    HasUserImage = true;
                }
                else
                {
              

                    if (HasUserImage == false)
                    {
                        FancyPhoto.ImageUrl = ImageUrl;
                        UPL_NAME.Text = PhotoEmptyText;
                       
                    }
                }
     

                MasterUserPanel.Visible = CMS.Functions.IsMasterUser();
            }
        }

        if (Action == CMD.Delete)
        {
            DisableControls.DisableControl(this.Form);
        }

        if (Action == CMD.Insert)
        {
            FancyPhoto.ImageUrl = ImageUrl;
            DownloadPicture.Visible = false;
            UPL_NAME.Text = PhotoEmptyText;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        DownloadPicture.Visible = FancyPhoto.ImageUrl == ImageUrl ? false : true;

        if (Action == CMD.Update)
        {
            BtnSave.Text = "Edit";
        }
        else if (Action == CMD.Delete)
        {
            BtnSave.Text = "Delete";
            RemoveFancy = "$('img#" + FancyPhoto.ClientID + "').addClass('Opacity');$('a#inline').removeAttr('href');if(false)";
            USR_PASSWORD.TextMode = TextBoxMode.SingleLine;
        }
 
        FancyUploadPanel.Visible = CMS.Functions.AdministrationID != null;
        FileNamePanel.Visible = CMS.Functions.AdministrationID != null;
        
        ((Content)Master).Jscript = null;

    }

    public String hashPassword;
    public String RestrictedPassword;
    void UserPassword(Boolean ValidPassword)
    {
        if (ValidPassword)
        {
            hashPassword = CMS.Functions.Hash.ComputeHash(RestrictedPassword, "MD5", null);
        }
    }

    public Boolean Policy()
    {
        RestrictedPassword = CMS.Functions.PasswordPolicy(8, USR_PASSWORD.Text, "The minimum length of a password must be atleast 8 characters and not " + USR_PASSWORD.Text.Length + "", "$('.PasswordPolicy').css('border', '1px solid White').css('color','White').css('background-color','#f59e13');", System.Drawing.KnownColor.Black);
        return !String.IsNullOrEmpty(RestrictedPassword);
    }

    void Values(Int64 Action)
    {
        if (Action == CMD.Insert)
        {
            UserPassword(Policy());

            Results = CMS.StoredProcedureValues.SP_User(CMD.Insert, UserID, CMS.Functions.AdministrationID, USR_NAME.Text, hashPassword, USR_EMAIL.Text, USR_ACTIVE.Checked, null,USR_MASTERUSER.Checked);

            if (Results.Error != 2601)
            {

                if (Results.Error == 0)
                {
                    HaveSaved = true;
                    ((Content)Master).Jscript = FancyPhoto.ImageUrl == ImageUrl ? CMS.Functions.NormalPopup("Inserted succesfully !") : CMS.Functions.ConfirmPopup("Inserted succesfully !", "Users.aspx", System.Drawing.KnownColor.Black);
                }
                else
                {
                    HaveSaved = false;
                    ((Content)Master).Jscript = CMS.Functions.NormalPopup(Results.Message, System.Drawing.KnownColor.Red);
                }
            }
            else
            {
                ((Content)Master).Jscript = CMS.Functions.NormalPopup("Login already exsists with this email : " + USR_EMAIL.Text + "<br /> please choose a different email !", System.Drawing.KnownColor.Black, "$('.Email').css('border', '1px solid Black').css('color','White').css('background-color','#bb5342');");
            }
        }

        if (Action == CMD.Update)
        {
            UserPassword(Policy());

            Results = CMS.StoredProcedureValues.SP_User(CMD.Update, UserID, CMS.Functions.AdministrationID, USR_NAME.Text, hashPassword, USR_EMAIL.Text, USR_ACTIVE.Checked, null, USR_MASTERUSER.Checked);

            if (Results.Error != 2601)
            {
                if (Results.Error == 0)
                {
                    ((Content)Master).Jscript = CMS.Functions.ConfirmPopup("Updated succesfully !", "Users.aspx", System.Drawing.KnownColor.Black);
                }
                else
                {
                    ((Content)Master).Jscript = CMS.Functions.NormalPopup(Results.Message, System.Drawing.KnownColor.Red);
                }
            }
            else
            {
                ((Content)Master).Jscript = CMS.Functions.NormalPopup("Login already exsists with this email : " + USR_EMAIL.Text + "<br /> please choose a different email !", System.Drawing.KnownColor.Black, "$('.Email').css('border', '1px solid Black').css('color','White').css('background-color','#bb5342');");
            }
        }

        if (Action == CMD.Delete)
        {
            Results = CMS.StoredProcedureValues.SP_User(CMD.Delete, UserID, CMS.Functions.AdministrationID, null, null, null, null, null, null);

            if (Results.Error == 0)
            {
                ((Content)Master).Jscript = CMS.Functions.ConfirmPopup("Deleted succesfully !", "Users.aspx", System.Drawing.KnownColor.Black);
            }
            else
            {
                ((Content)Master).Jscript = CMS.Functions.NormalPopup(Results.Message, System.Drawing.KnownColor.Red);
            }

            if (ConfigurationManager.AppSettings["UserCanDeleteImageFromDisk"].ToString() == "True")
            {
                if (FancyPhoto.ImageUrl != ImageUrl)
                {
                    CMS.StoredProcedureValues.SP_Upload(CMD.Delete, CMS.Functions.AdministrationID, null, UserID, null, null, null);
                    File.Delete(Server.MapPath(".") + "\\" + FancyPhoto.ImageUrl);
                }
                else
                {
                    CMS.StoredProcedureValues.SP_Upload(CMD.Delete, CMS.Functions.AdministrationID, null, UserID, null, null, null);
                }
            }
        }

    }

    void HandleErrorMessages()
    {
        ((Content)Master).Jscript =
        String.IsNullOrEmpty(USR_NAME.Text) ? CMS.Functions.NormalPopup("Please enter Username !",
        System.Drawing.KnownColor.Black,
        " $('.Username').css('border', '1px solid White').css('color','White').css('background-color','#f59e13');") :
        String.IsNullOrEmpty(USR_EMAIL.Text) ? CMS.Functions.NormalPopup("Please enter Email !",
        System.Drawing.KnownColor.Black,
        " $('.Email').css('border', '1px solid White').css('color','White').css('background-color','#f59e13');") :
        String.IsNullOrEmpty(USR_PASSWORD.Text) ? CMS.Functions.NormalPopup("Please enter Password !",
        System.Drawing.KnownColor.Black,
        " $('.Password').css('border', '1px solid White').css('color','White').css('background-color','#f59e13');") : null;
    }

    protected void BtnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("Users.aspx");
    }

    protected void BtnDownload_Click(object sender, EventArgs e)
    {
        WebClient req = new WebClient();
        Response.Clear();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.Buffer = true;
        Response.AddHeader("Content-Disposition", "attachment;filename=\"" + UPL_NAME.Text + " " + ConfigurationManager.AppSettings["ApplicationName"].ToString() + ".jpg");
        byte[] data = req.DownloadData(Server.MapPath(".") + "\\" +  FancyPhoto.ImageUrl);
        Response.BinaryWrite(data);
        Response.End();
    }

    

    protected void BtnSubmit_Click(object sender, EventArgs e)
    {
        if (Action != CMD.Delete)
        {
            if (!String.IsNullOrEmpty(USR_NAME.Text) && !String.IsNullOrEmpty(USR_PASSWORD.Text) && !String.IsNullOrEmpty(USR_EMAIL.Text))
            {
                if (CMS.Functions.GetEmailAddress(USR_EMAIL.Text) != null)
                {
                    if (Policy())
                    {
                        Values(Action);
                    }
                    else
                    {
                        ((Content)Master).Jscript = CMS.Functions.IsError;
                    }
                }
                else
                {
                    ((Content)Master).Jscript = CMS.Functions.NormalPopup("Email is not valid !", System.Drawing.KnownColor.Black, "$('.ValidEmail').css('border', '1px solid White').css('color','White').css('background-color','#f59e13');");
                }
            }
            else
            {
                HandleErrorMessages();
            }
        }
        else
        {
          Values(Action);
        }
    }

    public string upl_guid = System.Guid.NewGuid().ToString();

    void SaveValues()
    {
        var GetPicture = CMS.Uploads.GetUpload(CMS.Functions.AdministrationID, null, UserID, null, null, null).SingleOrDefault();

        File.Delete(Server.MapPath(".") + "\\Uploads\\Pictures\\" + CMS.Functions.Administrationname + "\\" + GetPicture.UPL_GUID + ".jpg");
        string savePath = Server.MapPath(".") + "\\Uploads\\Pictures\\" + CMS.Functions.Administrationname + "\\";
        
        string Extension = "";


        if (!System.IO.Directory.Exists(savePath))
        {
            System.IO.Directory.CreateDirectory(savePath);
            Extension = Path.GetExtension(savePath);
        }
        savePath = savePath + upl_guid + ".jpg";
        FuPhoto.SaveAs(savePath);
        savePath = "";
        savePath = "Uploads\\Pictures\\" + CMS.Functions.Administrationname + "\\";

        if (GetPicture != null)
        {
            FancyPhoto.ImageUrl = savePath + GetPicture.UPL_GUID + ".jpg";
            if (FancyPhoto.ImageUrl != ImageUrl)
            {
                ((Content)Master).FancyPhotoheader(UserID, savePath + GetPicture.UPL_GUID + ".jpg");
                FillValues();
            }
            else
            {
                ((Content)Master).FancyPhotoheader(UserID, ImageUrl);
                FillValues();
            }
        }

    }

    public Boolean? Havesaved;
    public Boolean? HaveSaved
    {
        get { return Havesaved; }
        set { Havesaved = value; }
    }

    protected void ButtonUpload_Click(object sender, EventArgs e)
    {
        if (CMS.Rights.UPL)
        {
            string filenaam = FuPhoto.FileName;

            if ((FuPhoto.HasFile))
            {
                if (Action == CMD.Insert)
                {
                    if (HaveSaved.HasValue)
                    {
                        ((Content)Master).Jscript = CMS.Functions.NormalPopup("Create/Save user account first !");
                        return;
                    }
                    else
                    {
                        if (!String.IsNullOrEmpty(USR_NAME.Text) && !String.IsNullOrEmpty(USR_EMAIL.Text))
                        {
                            var aUser = CMS.Users.GetUsers(null, USR_NAME.Text, null, USR_EMAIL.Text, CMS.Functions.AdministrationID, USR_ACTIVE.Checked, null, USR_MASTERUSER.Checked).SingleOrDefault();
                            UserID = aUser.USR_ID;
                        }
                        else
                        {

                            ((Content)Master).Jscript = CMS.Functions.NormalPopup("Create/Save user account first !");
                            return;
                        }
                    }
                }

                UPL_NAME.Text = filenaam.Remove(filenaam.Length - 4, 4);
                PictureNameFull = filenaam.Remove(filenaam.Length - 4, 4);

                StoredProcedureValues Results = new StoredProcedureValues();
                Results = CMS.StoredProcedureValues.SP_Upload(CMD.Insert, CMS.Functions.AdministrationID, null, UserID, UPL_NAME.Text, upl_guid, null);
                DownloadPicture.Visible = FancyPhoto.ImageUrl == ImageUrl ? true : false;
                if (Results.Error != 2601)
                {
                    if (Results.Error == 0)
                    {
                        SaveValues();
                    }
                    else
                    {
                        ((Content)Master).Jscript = CMS.Functions.NormalPopup(Results.Message);
                    }
                }
                else
                {
                    SaveValues();
                    CMS.StoredProcedureValues.SP_Upload(CMD.Update, CMS.Functions.AdministrationID, null, UserID, UPL_NAME.Text, upl_guid, null);
                    FillValues();
                }
            }
            else
            {
                ((Content)Master).Jscript = CMS.Functions.NormalPopup("No image selected !");
                return;
            }
        }
        else
        {
            ((Content)Master).Jscript = CMS.Functions.NormalPopup("You dont have permissions to upload <br /> contact a MasterUser !");
            return;
        }
    }

    protected void ButtonDelete_Click(object sender, EventArgs e)
    {
        if (CMS.Rights.UPL)
        {

            if (FancyPhoto.ImageUrl != "" && FancyPhoto.ImageUrl != ImageUrl)
            {
                if (ConfigurationManager.AppSettings["UserCanDeleteImageFromDisk"].ToString() == "True")
                {
                    File.Delete(Server.MapPath(".") + "\\" + FancyPhoto.ImageUrl);
                }

                FancyPhoto.ImageUrl = "";
                FancyPhoto.ImageUrl = ImageUrl;
                StoredProcedureValues Results = new StoredProcedureValues();
                var GetPicture = CMS.Uploads.GetUpload(CMS.Functions.AdministrationID, null, UserID, null, null, null).FirstOrDefault();

                Results = CMS.StoredProcedureValues.SP_Upload(CMD.Delete, CMS.Functions.AdministrationID, null, UserID, null, null, null);
                ((Content)Master).Jscript = Results.Error == 0 ? CMS.Functions.NormalPopup("Delete succes !") : CMS.Functions.NormalPopup(Results.Message);
                DownloadPicture.Visible = FancyPhoto.ImageUrl == ImageUrl ? false : true;
                ((Content)Master).FancyPhotoheader(UserID, ImageUrl);
                UPL_NAME.Text = "";
                UPL_NAME.Text = PhotoEmptyText;
            }
        }
        else
        {
            ((Content)Master).Jscript = CMS.Functions.NormalPopup("You dont have permissions to delete uploads <br /> contact a MasterUser !");
            return;
        }
    }

}